package com.carassistant.beta.dog;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.carassistant.beta.R;
import com.carassistant.beta.common.CarAssistantActivity;

public class DogMainActivity extends CarAssistantActivity {
	private RelativeLayout root;
	private TextView curSpeed;
	
	private LocationManager locationManager;
	private LocationListener locationListener;
	
	private Handler mHandler;
	
	private static final int MESSAGE_SPEED = 1; 
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dog_main);
		
		init();
	}
	
	private void init(){
		root = (RelativeLayout) findViewById(R.id.root);
		root.addView(getHeaderInstance(CarAssistantActivity.HEAD_HAVE_BACK, "测速仪"));
		curSpeed = (TextView) findViewById(R.id.curSpeed);
		curSpeed.setTextSize(getSize(40));
		
		listenSpeed();
		
		mHandler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case MESSAGE_SPEED:
					curSpeed.setText(""+msg.arg1);
					break;

				default:
					break;
				}
			}
		};
		
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 50, 0.0F, locationListener); //每秒更新位置信息，不考虑距离变化
	}
	
	//监听速度是否发生变化
  	private void listenSpeed(){
  		locationListener = new LocationListener() {
  			public void onProviderDisabled(String provider) {

  			}

  			public void onProviderEnabled(String provider) {

  			}

  			public void onStatusChanged(String provider, int status,
  					Bundle extras) {
  			}

  			public void onLocationChanged(Location location) {
  				float speedKM = location.getSpeed()*3.6f;
  				mHandler.obtainMessage(MESSAGE_SPEED, (int)speedKM,0).sendToTarget();
  			}
  		};
  	}
  	
  	@Override
  	protected void onDestroy() {
  		super.onDestroy();
  		
  		locationManager.removeUpdates(locationListener);
  	}
}
